package com.asman.vr.network

import com.asman.vr.dto.BaseResNull
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import com.asman.vr.constant.ErrorCode
// todo sp
//import sp
//import spExit

abstract class MyRetrofitCallbackNull(private val interceptCodeError: Boolean = false) :
    Callback<BaseResNull> {

    enum class ErrorType {
        CodeError, NetWorkError,
    }

    override fun onFailure(call: Call<BaseResNull>, t: Throwable) {
        onError(ErrorType.NetWorkError, call, "", "网络异常，请检查网络")
    }

    override fun onResponse(call: Call<BaseResNull>, response: Response<BaseResNull>) {
        if (response.isSuccessful) {
            if (response.body()?.code == ErrorCode._10000) {
                onSuccess(call, response.body()?.datetime ?: "0")
            } else {
                //是否拦截code error的情况下的默认操作--比如为true时，不进行跳转登录页面
                if (!interceptCodeError) {
                    if (ErrorCode.tokenLoseEfficacy(response.body()?.code)) { //token 失效了
                        // todo
                        // sp.spExit()
                        // todo 跳转登陆
                        /*RouterUtils.get(RouterUrl.LoginChoiceActivity)
                            .navigation()*/
                    }
                }
                onError(
                    ErrorType.CodeError, call, response.body()?.code ?: "",
                    response.body()?.error ?: "出了一点小差，请稍后重试"
                )
            }
        } else {
            onError(
                ErrorType.NetWorkError, call, response.body()?.code ?: "",
                "网络异常，请检查网络"
            )
        }
    }

    abstract fun onSuccess(call: Call<BaseResNull>, datetime: String) //状态码成功

    //除了success的所有error
    open fun onError(errorType: ErrorType, call: Call<BaseResNull>, code: String, msg: String) {
        if (errorType == ErrorType.CodeError) {
            onCodeError(call, code, msg)
        } else if (errorType == ErrorType.NetWorkError) {
            onNetWorkError(call, msg)
        }
    }

    //状态码错误
    open fun onCodeError(call: Call<BaseResNull>, code: String, msg: String) {}

    //网络错误
    open fun onNetWorkError(call: Call<BaseResNull>, msg: String) {}

}